<template>
	<view>
		<fileSelect @fileChange="handleFileSelectChange">
			<button type="default">账本导入</button>
		</fileSelect>
		<button type="default" @click="exportTempllate">模板下载</button>
		<button type="default" @click="exportDate">账本导出</button>
	</view>
</template>

<script>
	// import {
	// 	shareWithSystem
	// } from '@/uni_modules/jagger-share'
	import config from "@/configs/config"
	import dbOper from '@/module/accountSqlOper'
	import {
		getExcelOneSheetStr,
		parseXlsx
	} from "@/utils/excelExport.js"
	import {
		requestFileSystem,
		getFile,
		createWriter,
		writerStrToFile
	} from "@/utils/plusIoPromise.js"
	import modal from "@/utils/modal.js"
	import * as XLSX from 'xlsx'

	export default {
		data() {
			return {
				headers: ['序号', '姓名', '金额', '地址', '日期', '账本', '说明'],
				filedMap: {
					serial_no: '序号',
					name: '姓名',
					money: '金额',
					address: '地址',
					date: '日期',
					source: '账本',
					remark: '说明'
				}
			}
		},
		onShow() {},
		methods: {
			exportDate() { //导出数据
				const listData = []
				dbOper.getList("", 1000000, 1)
					.then(res => {
						let listData = []
						for (let row of res) {
							const data = [row.serial_no, row.name, row.money, row.address, row.date, row.source, row
								.remark
							]
							listData.push(data)
						}
						let sheetStr = getExcelOneSheetStr(this.headers, listData, "账本信息")
						// doExport("导出", this.headers, listData)
						const fileName = `账本信息_${Date.now()}.xlsx`
						return this.exportDataToExcel(fileName, sheetStr)
					})
			},
			exportTempllate() { //导出账本
				// doExport("导出", this.headers, [])
				const fileName = `模板信息_${Date.now()}.xlsx`
				let sheetStr = getExcelOneSheetStr(this.headers, [], "账信息")
				return this.exportDataToExcel(fileName, sheetStr)
			},
			exportDataToExcel(fileName, fileDataStr) { //导出数据到Excel
				let directoryPath = ""
				let filePath = ""
				requestFileSystem(plus.io.PRIVATE_DOC)
					.then(fileSystem => {
						directoryPath = fileSystem.root.toLocalURL()
						return getFile(fileSystem.root, "导出/" + fileName, {
							create: true
						})
					})
					.then(fileEntry => {
						filePath = fileEntry.toURL()
						return createWriter(fileEntry)
					})
					.then(fileWriter => {
						return writerStrToFile(fileWriter, fileDataStr)
					})
					.then(res => {
						// 新增确认弹窗
						uni.showModal({
							title: '导出成功',
							content: `文件已保存到: ${filePath}\n是否立即查看？`,
							confirmText: '立即查看',
							cancelText: '稍后查看',
							success: (res) => {
								if (res.confirm) {
									uni.openDocument({
										filePath,
										fail: (err) => {}
									})
								}
							}
						})
					})
					.catch(err => {
						uni.showToast({
							title: `导出失败: ${err}`,
							icon: 'none'
						})
					})
			},
			handleFileSelectChange(files) { //导入账本
				let base64Data = files.tempFiles[0].path
				let workbook = this.parseExcelBase64ToWorkbook(base64Data)
				// 获取表格数据（保留中文标题）
				let tableData = parseXlsx(workbook);
				// 更新状态
				let dbList = this.tableFieldToDbTield(tableData, this.filedMap)
				modal.confirm("发现" + dbList.length + "条数据，是否将原来数据删除并导入新数据！")
					.then(res => {
						console.log("dbList", dbList);
						dbOper.batchInsert(dbList)
					})
			},
			parseExcelBase64ToWorkbook(excelBase64) { //将Base64的Excel文件数据转换成workbook对象方便后续操作
				// 移除Data URL前缀
				const dataBase64 = excelBase64.split(',')[1];
				// 转换为ArrayBuffer
				const dataArrayBuffer = uni.base64ToArrayBuffer(dataBase64);
				// 解析Excel，添加多种编码支持
				console.log("XLSX", XLSX);
				let workbook = XLSX.read(dataArrayBuffer, {
					type: 'array'
				});
				console.log("workbook", workbook);
				return workbook
			},
			tableFieldToDbTield(excelJsonList, filedMap) { //将表格中文字段的JSON转换成数据库中英文字段JSON
				let dbJsonList = []
				for (let row of excelJsonList) {
					let newJson = {}
					for (let field in filedMap) {
						newJson[field] = row[filedMap[field]]
					}
					dbJsonList.push(newJson)
				}
				return dbJsonList;
			}
		}
	}
</script>

<style>

</style>